import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import org.apache.log4j.BasicConfigurator;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;

import com.spinn3r.log5j.Logger;


public class NetworkManager {
	
	
	private List<PcapIf> alldevs = new ArrayList<PcapIf>();
	private StringBuilder errbuf = new StringBuilder();
	private static Logger logger;
	
	public NetworkManager() {
		logger = Logger.getLogger(this.getClass());
	}
	
	public void init() {
		
		int rc = Pcap.findAllDevs(alldevs, errbuf);
		if (rc == Pcap.NOT_OK || alldevs.isEmpty()) {
			logger.error("Can't read list of devices, error is " +  errbuf.toString());
			return;
		}
		
		logger.info("Network devices found: ");
		int i =0;
		for (PcapIf device : alldevs) {
			logger.info("#%d: %s [%s]\n", i++, device.getDescription(), device.getName());
		}
	}
	
	public void activate(int i) throws ArrayIndexOutOfBoundsException {
		PcapIf device;
		device = alldevs.get(i);
		System.out.printf("Activating: %s", device.getDescription());
		Pcap pcap = Pcap.openLive(device.getName(), 64 * 1024, 0, 10000, errbuf);
		new Thread(new NetworkAdapter(pcap)).start();
		if (pcap == null) {
			logger.error("Error while opening device for capture: %s", errbuf.toString());
			return;
		}
			
	}
	
	public static void main(String args[]) {
		BasicConfigurator.configure();
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
		NetworkManager manager = new NetworkManager();
		manager.init();
		System.out.printf("Select device: ");
		String input;
		try {
			input = stdin.readLine();
			System.out.printf("selected %s\n", input);
			manager.activate(Integer.parseInt(input));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
